import React, { useRef, useState } from 'react';

const ImageWithButton: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [isImageClicked, setIsImageClicked] = useState(false);
  const [isButtonClicked, setIsButtonClicked] = useState(false);

  const handleImageClick = () => {
    setIsImageClicked(true);
  };

  const handleButtonClick = () => {
    setIsButtonClicked(true);
    removeBackgroundColor();
  };

  const removeBackgroundColor = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const image = new Image();
    image.src = 'your-image-url.jpg'; // 替换为你的图片URL

    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      ctx.drawImage(image, 0, 0);

      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;

      // 简单的抠图算法，假设背景色为白色
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        // 如果颜色接近白色，则设置为透明
        if (r > 200 && g > 200 && b > 200) {
          data[i + 3] = 0; // 设置透明度为0
        }
      }

      ctx.putImageData(imageData, 0, 0);
    };
  };

  return (
    <div>
      <canvas ref={canvasRef} style={{ display: isButtonClicked ? 'block' : 'none' }} />
      <img
        src="https://ts2.cn.mm.bing.net/th?id=ORMS.79a1d2085e5b1842b2ed7d535141d6ed&pid=Wdp&w=268&h=140&qlt=90&c=1&rs=1&dpr=1&p=0" // 替换为你的图片URL
        alt="Clickable Image"
        style={{ cursor: 'pointer' }}
        onClick={handleImageClick}
      />
      {isImageClicked && !isButtonClicked && (
        <button onClick={handleButtonClick}>去除背景色</button>
      )}
    </div>
  );
};

export default ImageWithButton;